/*
    koa-router中间件获取post方法参数
*/

const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const fs = require('fs');
const path = require('path');

const app = new Koa();
const router = new Router();

router
    .get('/', async ctx => {
        const html = `
            <h1>Request Post</h1>
            <form method="post" action="/">
                <p>userName</p>
                <input name="userName" /><br/>
                <p>age</p>
                <input name="age" /><br/>
                <p>email</p>
                <input name="email" /><br/>
                <button type="submit">提交</button>
            </form>
        `;
        ctx.body = html;
    })
    .get('/path', async ctx => {
        ctx.body = path.resolve();
    })
    .get('/todo', async ctx => {
        const url = ctx.url;
        let p = path.resolve() 
        const relativePath = `${p}/page${url}.html`;
        const file = new Promise((resolve,reject) => {
                        fs.readFile(relativePath,'utf-8',(err,data) => {
                            if (err) {
                                reject(err);
                            } else {
                                resolve(data);
                            }
                        });
                    });
        ctx.body = await file;
    })
    .post('/', async ctx => {
        ctx.body = ctx.request.body;
    })

app
    .use(bodyParser())
    .use(router.routes())
    .use(router.allowedMethods());

app.listen(3000, () => {
    console.log('[Server] is running at port 3000 .');
});